<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件

function alert($msg)
{
    header('Content-type: text/html; charset=UTF-8');
    $json = new \app\common\lib\servicesJSON();
    echo $json->encode(array('error' => 1, 'message' => $msg));
    exit;
}

function upshow($status, $data = [], $httpCode = 200)
{
    $data = [
        'error' => $status,
        'url' => $data
    ];
    return json($data);
}

/**
 * 通用化API接口数据输出
 * @param int $status 业务状态码
 * @param string $message 信息提示
 * @param [] $data  数据
 * @param int $httpCode http状态码
 * @return array
 */
function show($status, $message, $data = [], $httpCode = 200)
{
    $data = [
        'status' => $status,
        'message' => $message,
        'data' => $data,
    ];

    return json($data, $httpCode);
}

//配合layui输出表格数据

function showTable($status, $message, $count = 0, $data = [], $httpCode = 200)
{
    $data = [
        'code' => $status,
        'msg' => $message,
        'count' => $count,
        'data' => $data,
    ];
    return json($data, $httpCode);
}


//打印函数

function p($var)
{
    if (is_bool($var)) {
        var_dump($var);
    } elseif (is_null($var)) {
        var_dump(null);
    } else {
        echo "<pre style='position:relative;z-index:1000;padding:10px;border-radius:5px;background:#F5F5F5;border:1px solid #aaa;font-size:14px;line-height:18px;opacity:0.9;'>" . print_r($var, true) . "</pre>";
    }
}

/**
 * 获取文件目录列表
 * @param string $pathname 路径
 * @param integer $fileFlag 文件列表 0所有文件列表,1只读文件夹,2是只读文件(不包含文件夹)
 * @param string $pathname 路径
 * @return array
 */
function get_file_folder_List($pathname, $fileFlag = 0, $pattern = '*')
{
    $fileArray = array();
    $pathname = rtrim($pathname, '/') . '/';
    $list = glob($pathname . $pattern);
    foreach ($list as $i => $file) {
        switch ($fileFlag) {
            case 0:
                $fileArray[] = basename($file);
                break;
            case 1:
                if (is_dir($file)) {
                    $fileArray[] = basename($file);
                }
                break;

            case 2:
                if (is_file($file)) {
                    $fileArray[] = basename($file);
                }
                break;

            default:
                break;
        }
    }

    if (empty($fileArray)) {
        $fileArray = null;
    }

    return $fileArray;
}


//截取字符
function msubstr($str, $start = 0, $length, $charset = "utf-8", $suffix = true)
{
    if (function_exists("mb_substr")) {
        if ($suffix) {
            return mb_substr($str, $start, $length, $charset) . "...";
        } else {
            return mb_substr($str, $start, $length, $charset);
        }
    } elseif (function_exists('iconv_substr')) {
        if ($suffix) {
            return iconv_substr($str, $start, $length, $charset) . "...";
        } else {
            return iconv_substr($str, $start, $length, $charset);
        }
    }
    $re['utf-8'] = "/[x01-x7f]|[xc2-xdf][x80-xbf]|[xe0-xef]
                  [x80-xbf]{2}|[xf0-xff][x80-xbf]{3}/";
    $re['gb2312'] = "/[x01-x7f]|[xb0-xf7][xa0-xfe]/";
    $re['gbk'] = "/[x01-x7f]|[x81-xfe][x40-xfe]/";
    $re['big5'] = "/[x01-x7f]|[x81-xfe]([x40-x7e]|xa1-xfe])/";
    preg_match_all($re[$charset], $str, $match);
    $slice = join("", array_slice($match[0], $start, $length));
    if ($suffix) {
        return $slice . "…";
    }
    return $slice;
}

/**
 * 图片json字符串 转图片数组
 */
function get_picture_array($str_pictureurls)
{
    $pictureurls = json_decode($str_pictureurls, true);
    if (empty($pictureurls)) {
        $pictureurls = array();
    }

    return $pictureurls;
}

function get_pinyin($str, $ishead = 0, $isclose = 1, $lang = 'zh-cn')
{
    //global $pinyins;
    $pinyins = array();
    $restr = '';
    $str = trim($str);
    $slen = strlen($str);
    //$str=iconv("UTF-8","gb2312",$str);
    //echo $str;
    if ($slen < 2) {
        return $str;
    }
    $file = './public/pinyin-' . $lang . '.dat';
    if (!file_exists($file)) {
        $file = './public/pinyin-zh-cn.dat';
    }
    if (count($pinyins) == 0) {
        $fp = fopen($file, 'r');
        if (false == $fp) {
            return '';
        }
        while (!feof($fp)) {
            $line = trim(fgets($fp));
            $pinyins[$line[0] . $line[1]] = substr($line, 3, strlen($line) - 3);
        }
        fclose($fp);
    }

    for ($i = 0; $i < $slen; $i++) {
        if (ord($str[$i]) > 0x80) {
            $c = $str[$i] . $str[$i + 1];
            $i++;
            if (isset($pinyins[$c])) {
                if ($ishead == 0) {
                    $restr .= $pinyins[$c];
                } else {
                    $restr .= $pinyins[$c][0];
                }
            } else {
                $restr .= "x"; //$restr .= "_";
            }
        } elseif (preg_match("/[a-z0-9]/i", $str[$i])) {
            $restr .= $str[$i];
        } else {
            $restr .= "x"; //$restr .= "_";
        }
    }
    if ($isclose == 0) {
        unset($pinyins);
    }
    return $restr;
}

//tag变量整理，多变量字符串[主要针对 typeid  == -1后面自动获取]
function tag_param_vars_string($str, $delimiter = ',', $default_value = '-1')
{
    $str_value = '\'' . $default_value . '\'';
    if ($str == '' || is_null($str)) {
        return $str_value;
    }
    $tmp_arr = explode($delimiter, $str); //去除空数组'',0,再使用sort()重建索引
    if (empty($tmp_arr)) {
        return $str_value;
    }
    $arr = array();
    foreach ($tmp_arr as $k => $v) {
        $v = trim($v);
        if ($v == '') {
            continue;
        }
        if (stripos($v, '$') !== false) {
            $arr[] = $v;
        } else {
            $arr[] = '\'' . $v . '\'';
        }
    }
    return empty($arr) ? $str_value : implode(".','.", $arr);
}

//一维数组(同模型)(model_id)，删除其他模型的分类
function getLevelOfModelId($cate, $model_id = 0)
{
    $arr = array();
    foreach ($cate as $v) {
        if ($v['model_id'] == $model_id) {
            $arr[] = $v;
        }
    }

    return $arr;
}

function clearPageAndLink($cate, $model_id = 2, $type = 0)
{
    $arr = array();
    foreach ($cate as $v) {
        if ($v['model_id'] != $model_id && $v['type'] == $type) {
            $arr[] = $v;
        }
    }
    return $arr;
}

function toLayer($cate, $name = 'child', $pid = 0)
{
    $arr = array();
    foreach ($cate as $v) {
        if ($v['pid'] == $pid) {
            $v[$name] = toLayer($cate, $name, $v['id']);
            $arr[] = $v;
        }
    }

    return $arr;
}

function getSelf($cate, $id)
{
    $arr = array();
    foreach ($cate as $v) {
        if ($v['id'] == $id) {
            $arr = $v;
            return $arr;
        }
    }
    return $arr;
}

function create_folders($dir)
{
    return is_dir($dir) or (create_folders(dirname($dir)) and mkdir($dir, 0777));
}

function isMobile()
{
    // 如果有HTTP_X_WAP_PROFILE则一定是移动设备
    if (isset($_SERVER['HTTP_X_WAP_PROFILE'])) {
        return true;
    }
    // 如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
    if (isset($_SERVER['HTTP_VIA'])) {
        // 找不到为flase,否则为true
        return stristr($_SERVER['HTTP_VIA'], "wap") ? true : false;
    }
    // 脑残法，判断手机发送的客户端标志,兼容性有待提高
    if (isset($_SERVER['HTTP_USER_AGENT'])) {
        $clientkeywords = array('nokia',
            'sony',
            'ericsson',
            'mot',
            'samsung',
            'htc',
            'sgh',
            'lg',
            'sharp',
            'sie-',
            'philips',
            'panasonic',
            'alcatel',
            'lenovo',
            'iphone',
            'ipod',
            'blackberry',
            'meizu',
            'android',
            'netfront',
            'symbian',
            'ucweb',
            'windowsce',
            'palm',
            'operamini',
            'operamobi',
            'openwave',
            'nexusone',
            'cldc',
            'midp',
            'wap',
            'mobile'
        );
        // 从HTTP_USER_AGENT中查找手机浏览器的关键字
        if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT']))) {
            return true;
        }
    }
    // 协议法，因为有可能不准确，放到最后判断
    if (isset($_SERVER['HTTP_ACCEPT'])) {
        // 如果只支持wml并且不支持html那一定是移动设备
        // 如果支持wml和html但是wml在html之前则是移动设备
        if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html')))) {
            return true;
        }
    }
    return false;
}

//标题
function title_temp($data, $content)
{
    $cname = $data['cname'];
    $ename = $data['ename'];
    $value = $data['value'];
    $descript = $data['descript'];
    $validate = $data['validate'];
    $str = "";
    $validateStr = "";
    if ($validate == 1) {
        $str .= "<span style='color:red'>*</span>";
        $validateStr .= "lay-verify='required'";
    }
    $color = $ename . 'color';
    $val = isset($content[$ename]) ? $content[$ename] : '';
    $valcolor = isset($content[$color]) ? $content[$color] : '#333';
    $temp = <<<html
	<tr>
		<th style="text-align:right">
			{$cname} {$str}
		</th>
		<td>
			<input type="text" value="{$val}" style="width:90%;float: left;color:{$valcolor}" name="{$ename}" {$validateStr} autocomplete="off" placeholder="{$descript}" class="layui-input {$ename}">
			<span id="{$ename}" style="width:9%;float: left;padding-left:1%"></span>
			<input type="hidden" name="{$color}" value="{$valcolor}" />
		</td>
	</tr>
	<script>
		layui.use(['colorpicker'], function() {
			var colorpicker = layui.colorpicker;
				colorpicker.render({
					elem: '#{$ename}',
					color: '{$valcolor}', //设置默认色
					done: function(color){
					  $("input[name='{$color}']").val(color);
					  $("input[name='{$ename}']").css('color',color);
					}
				});
		})
	</script>
html;
    echo $temp;
}

//单行文本
function input_temp($data, $content)
{
    $type = $data['type'];
    $cname = $data['cname'];
    $ename = $data['ename'];
    $value = $data['value'];
    $descript = $data['descript'];
    $validate = $data['validate'];
    $str = "";
    $validateStr = "";
    if ($validate == 1) {
        $str .= "<span style='color:red'>*</span>";
        $validateStr .= "lay-verify='required'";
    }
    $val = isset($content[$ename]) ? $content[$ename] : "";
    if ($type == 1) {
        $inputtype = "text";
    } elseif ($type == 9) {
        $inputtype = "number";
        $val = isset($content[$ename]) ? $content[$ename] : 100;
    } elseif ($type == 19) {
        $inputtype = "tel";
    } elseif ($type == 18) {
        $inputtype = "email";
    } elseif ($type == 17) {
        $inputtype = "url";
    } else {
        $inputtype = "text";
    }

    $temp = <<<html
	<tr>
		<th style="text-align:right">{$cname} {$str}</th>
		<td>
			<input type="{$inputtype}" value="{$val}" style="min-width: 200px;float: left;margin-right: 5px;" name="{$ename}" {$validateStr} autocomplete="off" placeholder="{$descript}" class="layui-input">
		</td>
	</tr>
html;
    echo $temp;
}

//多行文本
function text_temp($data, $content)
{
    $cname = $data['cname'];
    $ename = $data['ename'];
    $value = $data['value'];
    $descript = $data['descript'];
    $validate = $data['validate'];
    $str = "";
    $validateStr = "";
    if ($validate == 1) {
        $str .= "<span style='color:red'>*</span>";
        $validateStr .= "lay-verify='required'";
    }
    $val = isset($content[$ename]) ? $content[$ename] : '';
    $temp = <<<html
	<tr>
		<th style="text-align:right">{$cname} {$str}</th>
		<td>
			<textarea placeholder="{$descript}" class="layui-textarea" {$validateStr} name="{$ename}">{$val}</textarea>
		</td>
	</tr>
html;
    echo $temp;
}

//单视频
function video_temp($data, $content)
{
    $cname = $data['cname'];
    $ename = $data['ename'];
    $value = $data['value'];
    $descript = $data['descript'];
    $validate = $data['validate'];
    $str = "";
    $validateStr = "";
    if ($validate == 1) {
        $str .= "<span style='color:red'>*</span>";
        $validateStr .= "lay-verify='required' lay-reqText='{$cname}必须上传'";
    }
    $val = empty($content[$ename]) ? "" : $content[$ename];

    $valpath = empty($content[$ename]) ? __ROOT__ . "public/admin/images/image.png" : $content[$ename] . '?vframe/jpg/offset/1';
    $url = url('/api/v1/index/up');
    $nurl = '/';
    $temp = <<<html
	<th style="text-align:right">{$cname} {$str}</th>
	<td>
		<div class="layui-upload">
			<button type="button" style="float: left;" class="layui-btn layui-btn-primary" id="{$ename}1">上传{$cname}</button>
			
			<div class="layui-upload-list">
				<img class="layui-upload-img" src="{$valpath}" id="{$ename}img">
				<p id="{$ename}pic"></p>
				
				<input type="hidden" name="{$ename}" {$validateStr} id="{$ename}logo" value="{$val}" />
			</div>
			
		</div>
		<div class="layui-progress" lay-filter="progressVideo">
		  <div class="layui-progress-bar layui-bg-blue"></div>
		</div>
	</td>
	<script>
		layui.use(['upload','element'], function() {
			
			var $ = layui.jquery,
				upload = layui.upload,
				element = layui.element;
			$(".layui-progress").hide();
			var index = "";
			//上传
			var uploadInst = upload.render({
				elem: "#{$ename}1",
				url: "{$url}",
				exts: 'mp4',
				number: 1,
				progress: function(n){
					$(".layui-progress").show();
					index = layer.load(1);
				    var percent = n + '%' //获取进度百分比
				    element.progress('progressVideo', percent);
				},
				done: function(res) {
					//如果上传失败
					if (res.code > 0) {
						return layer.msg('上传失败');
					} else {
						$("#{$ename}logo").val(res.data);
						var nurl = res.data;
						$("#{$ename}img").attr("src",nurl+'?vframe/jpg/offset/1');
						layer.close(index);
						$(".layui-progress").hide();
					}
					//上传成功
				},
				error: function() {
					
				}
			});
		});
	</script>
html;
    echo $temp;
}

//单图片
function thumb_temp($data, $content)
{
    $cname = $data['cname'];
    $ename = $data['ename'];
    $value = $data['value'];
    $descript = $data['descript'];
    $validate = $data['validate'];
    $str = "";
    $validateStr = "";
    if ($validate == 1) {
        $str .= "<span style='color:red'>*</span>";
        $validateStr .= "lay-verify='required'";
    }
    $val = empty($content[$ename]) ? "" : $content[$ename];

    $valpath = empty($content[$ename]) ? __ROOT__ . "public/admin/images/image.png" : $content[$ename];
    $url = url('/api/v1/index/up');
    $nurl = '';
    $temp = <<<html
	<th style="text-align:right">{$cname} {$str}</th>
	<td>
		<div class="layui-upload">
			<button type="button" style="float: left;" class="layui-btn layui-btn-primary" id="{$ename}1">上传{$cname}</button>
			<div class="layui-upload-list">
				<img class="layui-upload-img" src="{$valpath}" id="{$ename}img">
				<p id="{$ename}pic"></p>
				<input type="hidden" name="{$ename}" {$validateStr} id="{$ename}logo" value="{$val}" />
			</div>
		</div>
	
	</td>
	<script>
		layui.use(['upload'], function() {
			var $ = layui.jquery,
				upload = layui.upload;
			//普通图片上传
			var uploadInst = upload.render({
				elem: "#{$ename}1",
				url: "{$url}",
				number:1,
				done: function(res) {
					//如果上传失败
					if (res.code > 0) {
						return layer.msg('上传失败');
					} else {
						$("#{$ename}logo").val(res.data);
						var nurl = res.data;
						$("#{$ename}img").attr("src",nurl);
					}
					//上传成功
				},
				error: function() {
					
				}
			});
		});
	</script>
html;
    echo $temp;
}

//多图片
function thumbs_temp($data, $content)
{
    $cname = $data['cname'];
    $ename = $data['ename'];
    $value = $data['value'];
    $descript = $data['descript'];
    $validate = $data['validate'];
    $validateS = "";
    if ($validate == 1) {
        $validateS .= "<span style='color:red'>*</span>";
    }
    $val = isset($content[$ename]) ? $content[$ename] : '';
    $str = "";

    if (strlen($val) > 1) {
        $noption = explode(",", $val);

        foreach ($noption as $k => $v) {
            $imgsrc = $v;
            $str .= '<li class="item_img">';
            $str .= '<div class="operate">';
            $str .= '<i class="toleft layui-icon layui-icon-left"></i>';
            $str .= '<i class="toright layui-icon layui-icon-right"></i>';
            $str .= '<i class="close layui-icon layui-icon-delete"></i>';
            $str .= '</div>';
            $str .= "<img src='{$imgsrc}' class='img'>";
            $str .= "<input type='hidden' name='{$ename}[]' value='{$v}' />";
            $str .= '</li>';
        }
    }
    $valpath = '/' . $val;
    $url = url('/api/v1/index/up');
    $temp = <<<html
	<style>
		.pic-more { width:100%; left; margin: 10px 0px 0px 0px;}
		.pic-more li { width:90px; float: left; margin-right: 5px;}
		.pic-more li .layui-input { display: initial; }
		.pic-more li a { position: absolute; top: 0; display: block; }
		.pic-more li a i { font-size: 24px; background-color: #008800; }    
		#slide-pc-priview{$ename} .item_img img{ width: 90px; height: 90px;}
		#slide-pc-priview{$ename} li{position: relative;}
		#slide-pc-priview{$ename} li .operate{ color: #000; display: none;}
		#slide-pc-priview{$ename} li .toleft{ position: absolute;top: 40px; left: 1px; cursor:pointer;color:#fff}
		#slide-pc-priview{$ename} li .toright{ position: absolute;top: 40px; right: 1px;cursor:pointer;color:#fff}
		#slide-pc-priview{$ename} li .close{position: absolute;top: 5px; right: 5px;cursor:pointer;color:#fff}
		#slide-pc-priview{$ename} li:hover .operate{ display: block;}    
	</style>
	<th style="text-align:right">{$cname} {$validateS}</th>
	<td>
		<div class="layui-upload">
		  <button type="button" class="layui-btn layui-btn-primary pull-left" id="slide-pc{$ename}">选择多图</button>
		  <div class="pic-more">
			<ul class="pic-more-upload-list" id="slide-pc-priview{$ename}">
				{$str}
			</ul>
		  </div>
		</div>
	</td>
	<script>
	    layui.use('upload', function(){
	         var $ = layui.jquery;
	         var upload = layui.upload;            
			 upload.render({
				 elem: '#slide-pc{$ename}',
				 url: "{$url}",
				 size: 500,
				 methods:"POST",
				 exts: 'jpg|png|jpeg',
				 multiple: true,
				 number:9,
				 before: function(obj) {
					layer.msg('图片上传中...', {
							icon: 16,
							shade: 0.01,
							time: 0
					})
				 },
				 done: function(res) {
					layer.close(layer.msg());
					 if(res.status == 0) {
						 return layer.msg(res.message);
					 }
					 $('#slide-pc-priview{$ename}').append('<li class="item_img"><div class="operate"><i class="toleft layui-icon"></i><i class="toright layui-icon"></i><i  class="close layui-icon"></i></div><img src="' + res.data + '" class="img" ><input type="hidden" name="{$ename}[]" value="' + res.data + '" /></li>');
				 }
			 });
			});
			//点击多图上传的X,删除当前的图片    
			$("body").on("click",".close",function(){
				$(this).closest("li").remove();
			  });
			 //多图上传点击<>左右移动图片
			$("body").on("click",".pic-more ul li .toleft",function(){
				var li_index=$(this).closest("li").index();
				if(li_index>=1){
				  $(this).closest("li").insertBefore($(this).closest("ul").find("li").eq(Number(li_index)-1));
				}
			});
			$("body").on("click",".pic-more ul li .toright",function(){
				var li_index=$(this).closest("li").index();
				$(this).closest("li").insertAfter($(this).closest("ul").find("li").eq(Number(li_index)+1));
			});
	</script>
html;
    echo $temp;
}

//时间
function time_temp($data, $content)
{
    $cname = $data['cname'];
    $ename = $data['ename'];
    $value = $data['value'];
    $descript = $data['descript'];
    $validate = $data['validate'];
    $val = isset($content[$ename]) ? $content[$ename] : '0';
    $temp = <<<html
			<tr>
				<th style="text-align:right">{$cname}</th>
				<td>
					<input type="text" id="date{$ename}" lay-verify="datetime" placeholder="yyyy-MM-dd HH:mm:ss"
					 autocomplete="off" class="layui-input">
					 <input type="hidden" name="{$ename}" id="date{$ename}input">
				</td>
			</tr>
			<script>
				layui.use(['laydate'], function() {
					var nval = {$val}?{$val}:'';
					if(nval){
						if('{$ename}' == 'updatetime'){
							var adate = new Date();
						}else{
							var adate = new Date({$val}*1000);
						}
						
					}else{
						var adate = new Date();
					}
					var nvalue = adate.valueOf();
					$("#date{$ename}input").val(parseInt(nvalue/1000));
					laydate = layui.laydate;
					laydate.render({
						elem: '#date{$ename}',
						type: 'datetime',
						value: adate,
						format: 'yyyy-MM-dd HH:mm:ss',
						change:function(value){
							console.log(value)
							var nvalue = (new Date(value)).valueOf();
							$("#date{$ename}input").val(parseInt(nvalue/1000));
						}
					});
				})
			</script>
html;
    echo $temp;
}

//编辑器
function edit_temp($data, $content)
{
    $cname = $data['cname'];
    $ename = $data['ename'];
    $value = $data['value'];
    $descript = $data['descript'];
    $validate = $data['validate'];
    $str = "";
    $validateStr = "";
    if ($validate == 1) {
        $str .= "<span style='color:red'>*</span>";
        $validateStr .= "lay-verify='required'";
    }
    $val = isset($content[$ename]) ? $content[$ename] : '';
    $temp = <<<html
	<tr>
		<th style="text-align:right">{$cname} {$str}</th>
		<td>
			<textarea id="{$ename}" name="{$ename}" {$validateStr} style="height: 500px;width:100%">{$val}</textarea>
		</td>
	</tr>
	<script>
		var ue = UE.getEditor('{$ename}');
	</script>
html;
    echo $temp;
}

//mini编辑器
function mini_edit_temp($data, $content)
{
    $cname = $data['cname'];
    $ename = $data['ename'];
    $value = $data['value'];
    $descript = $data['descript'];
    $validate = $data['validate'];
    $str = "";
    $validateStr = "";
    if ($validate == 1) {
        $str .= "<span style='color:red'>*</span>";
        $validateStr .= "lay-verify='required'";
    }
    $val = isset($content[$ename]) ? $content[$ename] : '';
    $temp = <<<html
	<tr>
		<th style="text-align:right">{$cname} {$str}</th>
		<td>
			<textarea id="{$ename}" name="{$ename}" {$validateStr} style="height: 500px;width:100%">{$val}</textarea>
		</td>
	</tr>
	<script>
		var ue = UE.getEditor('{$ename}',{toolbars:[[
		        'fullscreen', 'source', '|', 'undo', 'redo', '|',
		        'bold', 'italic', 'underline', 'fontborder', 'strikethrough', 'pasteplain', '|', 'forecolor', 'backcolor', 'insertorderedlist', 'insertunorderedlist', 'selectall', 'cleardoc', '|',
		        'rowspacingtop', 'rowspacingbottom', 'lineheight', '|',
		        'customstyle', 'paragraph', 'fontfamily', 'fontsize', '|'
		    ]]})
	</script>
html;
    echo $temp;
}

//开关
function switch_temp($data, $content)
{
    $cname = $data['cname'];
    $ename = $data['ename'];
    $value = $data['value'];
    $descript = $data['descript'];
    $validate = $data['validate'];
    $val = isset($content[$ename]) ? $content[$ename] : '';
    $temp = <<<html
	<tr>
		<th style="text-align:right">{$cname}</th>
		<td>
			<input type="checkbox" checked="" value="1" name="{$ename}" lay-skin="switch" lay-filter="{$ename}" lay-text="ON|OFF">
		</td>
	</tr>
	<script>
		layui.use('form', function(){
		  var form = layui.form;
		  form.render();
		  form.on('switch({$ename})', function(data){
			  console.log(data);
			layer.tips('开关checked：'+ (this.checked ? 'true' : 'false'), data.othis)
		  });
		});
	</script>
html;

    echo $temp;
}

//单选
function radio_temp($data, $content)
{
    $cname = $data['cname'];
    $ename = $data['ename'];
    $value = $data['value'];
    $descript = $data['descript'];
    $validate = $data['validate'];
    $val = isset($content[$ename]) ? $content[$ename] : '';
    // p($val);
    $option = explode("|", $value);
    foreach ($option as $key => $v) {
        $noption[$key] = explode(",", $v);
    }
    // p($noption);
    $str = "";
    foreach ($noption as $k => $v) {
        if (isset($content[$ename])) {
            if ($k == 0) {
                $checked = ($val == 1) ? "checked" : "";
                $str .= "<input type='radio' name='{$ename}' value='$v[1]' title='$v[0]' {$checked}>";
            } else {
                $checked = ($val == 0) ? "checked" : "";
                $str .= "<input type='radio' name='{$ename}' value='$v[1]' title='$v[0]' {$checked}>";
            }
        } else {
            if ($k == 0) {
                $str .= "<input type='radio' name='{$ename}' value='$v[1]' title='$v[0]' checked>";
            } else {
                $str .= "<input type='radio' name='{$ename}' value='$v[1]' title='$v[0]'>";
            }
        }
    }
    $temp = <<<html
	<tr>
		<th style="text-align:right">{$cname}</th>
		<td>
			{$str}
		</td>
	</tr>
	<script>
		layui.use('form', function(){
		  var form = layui.form;
		  form.render();
		});
	</script>
html;

    echo $temp;
}

//多选
function checked_temp($data, $content)
{
    $cname = $data['cname'];
    $ename = $data['ename'];
    $value = $data['value'];
    $descript = $data['descript'];
    $validate = $data['validate'];
    $val = isset($content[$ename]) ? $content[$ename] : '';
    $varexplode = explode(",", $val);
    $validateStr = "";
    $str = "";
    if ($validate == 1) {
        $str .= "<span style='color:red'>*</span>";
        $validateStr .= "lay-verify='required'";
    }
    $option = explode("|", $value);
    foreach ($option as $key => $v) {
        $noption[$key] = explode(",", $v);
    }
    $strc = "";
    foreach ($noption as $k => $v) {
        $check = in_array($v[1], $varexplode) ? "checked" : "";
        $strc .= "<input type='checkbox' name='{$ename}[]' {$validateStr} lay-skin='primary' value='{$v[1]}' {$check} title='{$v[0]}'>";
    }
    $temp = <<<html
	<tr>
		<th style="text-align:right">{$cname} {$str}</th>
		<td>
			{$strc}
		</td>
	</tr>
	<script>
		layui.use('form', function(){
		  var form = layui.form;
		  form.render();
		});
	</script>
html;

    echo $temp;
}


/**
 * 将全角字符转为半角字符 如】转为]
 * @param type $str
 * @return type
 */
function toSemiangle($str)
{
    $arr = array('０' => '0', '１' => '1', '２' => '2', '３' => '3', '４' => '4',
        '５' => '5', '６' => '6', '７' => '7', '８' => '8', '９' => '9',
        'Ａ' => 'A', 'Ｂ' => 'B', 'Ｃ' => 'C', 'Ｄ' => 'D', 'Ｅ' => 'E',
        'Ｆ' => 'F', 'Ｇ' => 'G', 'Ｈ' => 'H', 'Ｉ' => 'I', 'Ｊ' => 'J',
        'Ｋ' => 'K', 'Ｌ' => 'L', 'Ｍ' => 'M', 'Ｎ' => 'N', 'Ｏ' => 'O',
        'Ｐ' => 'P', 'Ｑ' => 'Q', 'Ｒ' => 'R', 'Ｓ' => 'S', 'Ｔ' => 'T',
        'Ｕ' => 'U', 'Ｖ' => 'V', 'Ｗ' => 'W', 'Ｘ' => 'X', 'Ｙ' => 'Y',
        'Ｚ' => 'Z', 'ａ' => 'a', 'ｂ' => 'b', 'ｃ' => 'c', 'ｄ' => 'd',
        'ｅ' => 'e', 'ｆ' => 'f', 'ｇ' => 'g', 'ｈ' => 'h', 'ｉ' => 'i',
        'ｊ' => 'j', 'ｋ' => 'k', 'ｌ' => 'l', 'ｍ' => 'm', 'ｎ' => 'n',
        'ｏ' => 'o', 'ｐ' => 'p', 'ｑ' => 'q', 'ｒ' => 'r', 'ｓ' => 's',
        'ｔ' => 't', 'ｕ' => 'u', 'ｖ' => 'v', 'ｗ' => 'w', 'ｘ' => 'x',
        'ｙ' => 'y', 'ｚ' => 'z',
        '（' => '(', '）' => ')', '〔' => '[', '〕' => ']', '【' => '[',
        '】' => ']', '〖' => '[', '〗' => ']', '“' => '[', '”' => ']',
        '‘' => '[', '’' => ']', '｛' => '{', '｝' => '}', '《' => '<',
        '》' => '>',
        '％' => '%', '＋' => '+', '—' => '-', '－' => '-', '～' => '-',
        '：' => ':', '。' => '.', '、' => ',', '，' => ',', '、' => '.',
        '；' => ';', '？' => '?', '！' => '!', '…' => '-', '‖' => '|',
        '”' => '"', '’' => '`', '‘' => '`', '｜' => '|', '〃' => '"',
        '　' => ' ');

    return strtr($str, $arr);
}

/**
 * 根据PHP各种类型变量生成唯一标识号
 * @param mixed $mix 变量
 * @return string
 */
function to_guid_string($mix)
{
    if (is_object($mix)) {
        return spl_object_hash($mix);
    } elseif (is_resource($mix)) {
        $mix = get_resource_type($mix) . strval($mix);
    } else {
        $mix = serialize($mix);
    }
    return md5($mix);
}


//首页文章列表
function tpl_index($data)
{
    if (!isset($data['action'])) {
        return [];
    }
    $num = isset($data['num']) ? $data['num'] : 10;
    $order = isset($data['order']) ? $data['order'] : 'aid desc';
    $cache = isset($data['cache']) ? $data['cache'] : 1;
    $page = isset($data['page']) ? $data['page'] : '';
    $catid = isset($data['catid']) ? $data['catid'] : '';
    $field = isset($data['field']) ? $data['field'] : '*';

    $where = [];
    if ($catid) {
        $where['cid'] = $catid;
    }
    $where['status'] = 1;
    $rest = db('article')->where($where)->order($order)->field($field)->cache(arr_to_html($data), $cache, 'article')->limit($num)->select();
    return $rest;
}

function tpl_lists($data)
{
    if (!isset($data['action'])) {
        return [];
    }
    $num = isset($data['num']) ? $data['num'] : 10;
    $order = isset($data['order']) ? $data['order'] : 'aid desc';
    $cache = isset($data['cache']) ? $data['cache'] : 1;
    $page = isset($data['page']) ? $data['page'] : '';
    $catid = isset($data['catid']) ? $data['catid'] : '';
    $field = isset($data['field']) ? $data['field'] : '*';

    $where = [];
    if ($catid) {
        $where['cid'] = $catid;
    }
    $where['status'] = 1;
    $rest = db('article')->where($where)->order($order)->field($field)->cache('article1', $cache, 'article')->paginate($num);
    p($rest);
    die;
    return $rest;
}


function arr_to_html($data)
{
    if (is_array($data)) {
        $str = 'array(';
        foreach ($data as $key => $val) {
            if (is_array($val)) {
                $str .= "'$key'=>" . arr_to_html($val) . ",";
            } else {
                //如果是变量的情况
                if (strpos($val, '$') === 0) {
                    $str .= "'$key'=>$val,";
                } elseif (preg_match("/^([a-zA-Z_].*)\(/i", $val, $matches)) {
                    //判断是否使用函数
                    if (function_exists($matches[1])) {
                        $str .= "'$key'=>$val,";
                    } else {
                        $str .= "'$key'=>'" . newAddslashes($val) . "',";
                    }
                } else {
                    $str .= "'$key'=>'" . newAddslashes($val) . "',";
                }
            }
        }
        return $str . ')';
    }
    return false;
}

/**
 * 返回经addslashes处理过的字符串或数组
 * @param $string 需要处理的字符串或数组
 * @return mixed
 */
function newAddslashes($string)
{
    if (!is_array($string)) {
        return addslashes($string);
    }

    foreach ($string as $key => $val) {
        $string[$key] = newAddslashes($val);
    }

    return $string;
}

//排序
function cmp_func($a, $b)
{
    global $order;
    if ($a['is_dir'] && !$b['is_dir']) {
        return -1;
    } elseif (!$a['is_dir'] && $b['is_dir']) {
        return 1;
    } else {
        if ($order == 'size') {
            if ($a['filesize'] > $b['filesize']) {
                return 1;
            } elseif ($a['filesize'] < $b['filesize']) {
                return -1;
            } else {
                return 0;
            }
        } elseif ($order == 'type') {
            return strcmp($a['filetype'], $b['filetype']);
        } else {
            return strcmp($a['filename'], $b['filename']);
        }
    }
}


function hasChild($data, $cid, $fieldPid = 'pid')
{
    foreach ($data as $d) {
        if ($d[$fieldPid] == $cid) {
            return true;
        }
    }

    return false;
}

//获取字段模板
function get_feild($type)
{
    switch ($type) {

        case 2:
            $temp = <<<html
			<div class="layui-form-item">
				<label class="layui-form-label">选项</label>
					<div class="layui-input-inline">
						<textarea placeholder="请输入选项" lay-verify="required" name="value" class="layui-textarea">头条,1|推荐,2|置顶,3</textarea>
					</div>
					<div class="layui-form-mid layui-word-aux">例:头条,1|推荐,2|置顶,3</div>
			</div>
html;
            return $temp;
            break;
        case 5:
            $temp = <<<html
			<div class="layui-form-item">
				<label class="layui-form-label">选项</label>
				<div class="layui-input-inline">
					<textarea placeholder="请输入选项" lay-verify="required" name="value" class="layui-textarea">开启,1|关闭,0</textarea>
				</div>
				<div class="layui-form-mid layui-word-aux">例:开启,1|关闭,0</div>
			</div>
html;
            return $temp;
            break;
        case 4:
            $temp = <<<html
			<div class="layui-form-item">
				<label class="layui-form-label">选项</label>
				<div class="layui-input-inline">
					<textarea placeholder="请输入选项" lay-verify="required" name="value" class="layui-textarea">选项1,1|选项2,0</textarea>
				</div>
				<div class="layui-form-mid layui-word-aux">例:男,1|女,0</div>
			</div>
html;
            return $temp;
            break;
        case 7:
            $temp = <<<html
			<div class="layui-form-item">
				<label class="layui-form-label">选项</label>
				<div class="layui-input-inline">
					<textarea placeholder="请输入选项" lay-verify="required" name="value" class="layui-textarea">开启,1|关闭,0</textarea>
				</div>
				<div class="layui-form-mid layui-word-aux">例:开启,1|关闭,0</div>
			</div>
html;
            return $temp;
            break;
        default:
            return "";
    }
}


if (!function_exists('dd')) {
    function dd($data)
    {
        echo '<pre>';
        var_dump($data);
        die;
    }
}

/**
 * 获取本周所有日期
 */
function get_week($time = '', $format = 'Y-m-d')
{
    $time = $time != '' ? $time : time();
    //获取当前周几
    $week = date('w', $time);
    $date = [];
    for ($i = 1; $i <= 7; $i++) {
        $date[$i] = date($format, strtotime('+' . $i - $week . ' days', $time));
    }
    return $date;
}

/**
 * 获取一周日期
 * @param $time 时间戳
 * @param $format 转换格式
 */
function get_week_arr($time = 0, $format = "Y-m-d")
{
    if (!$time) {
        $time = time();
    }
    $week = date('w', $time);
    $weekname = array('星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期日');
    //星期日排到末位
    if (empty($week)) {
        $week = 7;
    }
    for ($i = 0; $i <= 6; $i++) {
        $currDay = $i + 1 - $week;
        $data[$i]['date'] = date($format, strtotime("+{$currDay} days", $time));
        $data[$i]['week'] = $weekname[$i];
    }
    return $data;
}
 